package app.web.admin.service.impl;

import app.web.admin.domain.ao.RoleCreateAo;
import app.web.admin.domain.ao.RolePatchByIdAo;
import app.web.admin.domain.pojo.AdminRole;
import app.web.admin.mapper.AdminRoleMapper;
import app.web.admin.mapper.AdminOfRoleMapper;
import app.web.admin.service.RoleService;
import com.gitee.feizns.quickstart.web.ex.BadRequestException;
import com.gitee.feizns.quickstart.web.restful.Rests;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 角色服务实现
 * @author feizns
 * @since 2025-04-09
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    /**
     * 角色 Mapper
     */
    private final AdminRoleMapper mapper;

    @Override
    public AdminRole create(RoleCreateAo ao) {
        return Rests.create(AdminRole.class, ao);
    }

    @Override
    public AdminRole patchById(Long id, RolePatchByIdAo ao) {
        AdminRole adminRole = Rests.getById(AdminRole.class, id);
        if ( !Objects.equals(adminRole.getName(), ao.getName()) ) {
//            if ( RoleMapper.exists(ao.getName(), role.getGroupId()) ) {
//                RoleGroup group = Rests.getById(RoleGroup.class, role.getGroupId());
//                throw new BadRequestException("角色组['%s']下已存在角色['%s'].".formatted(group.getName(), role.getName()));
//            }
        }
        return Rests.patchById(ao.copyPropertiesTo(AdminRole.class), id);
    }

    @Override
    public AdminRole deleteById(Long id) {
        if ( AdminOfRoleMapper.existsRoleId(id) )
            throw new BadRequestException("当前角色下存在用户，无法删除");
        return Rests.deleteById(AdminRole.class, id);
    }

}
